package com.ruoyi.mdkt.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.mdkt.entity.*;
import com.ruoyi.mdkt.entity.vo.RegistVo;
import com.ruoyi.mdkt.service.GoodsService;
import com.ruoyi.mdkt.service.PackService;
import com.ruoyi.mdkt.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gwl
 * @since 2022-10-22
 */
@CrossOrigin

@RestController
@RequestMapping("/mdkt/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private PackService packService;
    @Autowired
    private StudentService studentService;

    @GetMapping("/getGoodsList/{type}")
    public R getGoodsList(@PathVariable("type") Integer type){
        LambdaQueryWrapper<Goods> lambdaQueryWrapper=new LambdaQueryWrapper<Goods>();
        lambdaQueryWrapper.eq(Goods::getType,type);
        List<Goods> list = goodsService.list(lambdaQueryWrapper);
        return R.ok(list);
    }

    @PostMapping("/purchase/{userId}/{goodsId}")
    public R purchase(@PathVariable("userId") Long userId,@PathVariable("goodsId") Long goodsId){
        LambdaQueryWrapper<Goods> lambdaQueryWrapper=new LambdaQueryWrapper<Goods>();
        lambdaQueryWrapper.eq(Goods::getId,goodsId);
        Goods good = goodsService.getOne(lambdaQueryWrapper);
        LambdaQueryWrapper<Student> lambdaQueryWrapper1=new LambdaQueryWrapper<Student>();
        lambdaQueryWrapper1.eq(Student::getUserId,userId);
        Student student = studentService.getOne(lambdaQueryWrapper1);
        if(student.getAssets()>=good.getPrice()){
            LambdaQueryWrapper<Pack> lambdaQueryWrapper2=new LambdaQueryWrapper<Pack>();
            lambdaQueryWrapper2.eq(Pack::getUserId,userId);
            List<Pack> list = packService.list(lambdaQueryWrapper2);
            for (Pack pack : list) {
                if(pack.getGoodsId()!=goodsId){
                    Pack pack1=new Pack();
                    pack1.setUserId(userId);
                    pack1.setGoodsId(goodsId);
                    pack1.setNumber(1);
                    packService.save(pack1);
                }else{
                    pack.setNumber(pack.getNumber()+1);
                    packService.updateById(pack);
                }
                student.setAssets(student.getAssets()-good.getPrice());
                studentService.updateById(student);
            }
        }else{
            return R.fail("请赚够积分再来吧！");
        }

        return R.ok("购买成功");
    }



}

